﻿import 'package:get/get.dart';
import 'ProfileState.dart';
import 'package:azring/core/repository/default_api.dart';

/// 个人页控制器
class ProfileLogic extends GetxController {
  /// 状态实例
  final ProfileState state = ProfileState();

  @override
  void onInit() {
    super.onInit();
    // 先清空旧数据，避免显示上一个用户的信息
    state.username.value = '';
    state.email.value = '';
    state.avatar.value = '';
    state.groupList.clear();
    
    // 加载新用户数据
    _loadUserInfo();
    loadGroupList();
  }

  /// 加载群组列表
  Future<void> loadGroupList() async {
    try {
      state.isLoadingGroups.value = true;
      final response = await DefaultApi().queryGroupListGet();
      if (response != null && response['code'] == 200) {
        final data = response['data'] as List?;
        if (data != null) {
          state.groupList.value = data.map((item) => item as Map<String, dynamic>).toList();
        }
      }
    } catch (e) {
      print('加载群组列表失败: $e');
    } finally {
      state.isLoadingGroups.value = false;
    }
  }

  /// 重新排序群组
  Future<void> reorderGroups(int oldIndex, int newIndex) async {
    // 调整索引（Flutter的ReorderableListView需要这样处理）
    if (newIndex > oldIndex) {
      newIndex -= 1;
    }

    // 更新本地列表
    final item = state.groupList.removeAt(oldIndex);
    state.groupList.insert(newIndex, item);

    // 调用API更新排序
    try {
      final groupId = item['id'] as int;
      await DefaultApi().editGroupSortPut(id: groupId);
    } catch (e) {
      print('更新群组排序失败: $e');
      // 如果失败，恢复原来的顺序
      final item = state.groupList.removeAt(newIndex);
      state.groupList.insert(oldIndex, item);
    }
  }

  /// 加载用户信息
  Future<void> _loadUserInfo() async {
    try {
      final response = await DefaultApi().queryUserGet();
      if (response != null && response['code'] == 200) {
        final data = response['data'];
        
        // 更新用户名
        state.username.value = data['nickName'] ?? data['userName'] ?? '用户';
        
        // 更新邮箱
        state.email.value = data['email'] ?? '';
        
        // 处理头像URL - 拼接完整地址
        final avatar = data['avatar'];
        if (avatar != null && avatar.toString().isNotEmpty) {
          if (avatar.toString().startsWith('http')) {
            state.avatar.value = avatar;
          } else {
            // 拼接基础URL
            state.avatar.value = 'https://api.azlg.com/prod-api$avatar';
          }
        } else {
          // 清空头像
          state.avatar.value = '';
        }
      }
    } catch (e) {
      print('加载用户信息失败: $e');
      // 使用默认值
      state.username.value = '用户';
      state.email.value = '';
      state.avatar.value = '';
    }
  }

  /// 公共方法：重新加载用户信息
  Future<void> refreshUserInfo() async {
    await _loadUserInfo();
  }

  /// 编辑用户信息
  void editUserInfo() {
    state.isEditing.value = true;
  }

  /// 保存用户信息
  void saveUserInfo() {
    state.isEditing.value = false;
    // 这里可以添加保存逻辑
  }

  /// 取消编辑
  void cancelEdit() {
    state.isEditing.value = false;
    // 恢复原始数据
    _loadUserInfo();
  }

  /// 切换主题
  void toggleTheme() {
    state.isDarkMode.value = !state.isDarkMode.value;
    // 这里可以添加主题切换逻辑
  }

  /// 切换通知
  void toggleNotification() {
    state.isNotificationEnabled.value = !state.isNotificationEnabled.value;
  }
}
